import siteHeader from "./siteHeader.js";
import backTop    from "./backTop.js";
import banner     from "./banner.js";
import anthor     from "./anchor.js";
import render     from "./render.js";
import loaddata   from "./loaddata.js";
import starRoll   from "./star-roll.js";
import carts      from "./cart.js";
function index(){}
$.extend(index.prototype , {
    init : function(){
        var res      = loaddata.init();
        this.star_row  = $(".star-row");
        this.cHeight = $(window).height();
        this.timer   = null;
        this.sign   = $(".signin-btn");
        this.dLabel = $("#dLabel");

        res.then($.proxy(function(res){
            var data1  = JSON.parse(res).goods_list;
            var data2   = JSON.parse(res).goods_star;
            render.init(data1,data2);
            
            var star = render.renderStar(data2);

            $(this.star_row).html(star);

            var imgs = $(".layz");
            //设置图片懒加载高度
            $.each(imgs , $.proxy(function(index ,item){
                $(item).attr("data-top", $(item).offset().top);
            },this));
            //节流
            $(window).on("scroll",$.proxy(function(){
                clearTimeout(this.timer);
                this.timer = setTimeout($.proxy(function(){
                    var scrollTop = $("html,body").scrollTop();                          
                    this.loadImg(scrollTop,imgs); 
                    this.timer = null;  
                },this),100);
            },this));
            
            siteHeader.init();
            backTop.init();
            banner.init();
            anthor.init();
            starRoll.init();
            carts.init();
            this.validateTocken();
        },this));     
        
    },
    //懒加载的具体实现
    loadImg : function(scrollTop,imgs){
        $.each(imgs , $.proxy(function(index,item){
            var img_top = $(item).attr("data-top");
            if( scrollTop + this.cHeight >= img_top){
                var src = $(item).attr("data-original");
                // console.log(src);      
                $(item).attr("src",src);    
            }
        },this))      
    },
    validateTocken :function (){
        let url = "http://localhost/js/test/konka/php/login.php";
        $.ajax(url)
        .then( res => {
              res = JSON.parse(res)
              if(res.state){
                    return false;
              }        
              this.dLabel.html(res.username+",欢迎你");
              $(this.sign[0]).css("display","none");
              $(this.sign[1]).css("display","none");
              this.dLabel.on("click",function(){
                  $(".dropdown-menu").toggle(500);
              })
             
        })
    }
})
export default new index();